# -*- coding: utf-8 -*-
"""
@Time : 2023/7/28 15:39
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : query_all_books.py
"""

import sys
from flask_restful import Resource, reqparse

from service.mysql_connect import MySQLConnected
from service.config_import import load_yaml

sys.path.append('..')

# parser = reqparse.RequestParser()
# parser.add_argument('limit', type=int, help="不能为空", default=5000)


class QueryAllBooks(Resource):
    def post(self):
        # args = parser.parse_args()
        # limit = args.get('limit')
        yaml_config_path = "config_info.yaml"
        params = load_yaml(yaml_config_path)
        dbinfo = params['databases']['library_db_info']
        # print(dbinfo)
        db = params['databases']['library_db_name']
        # print(db)
        connected = MySQLConnected(dbinfo)
        # print(connected.con)
        # print(connected.cur)
        # sql = "select * from " + db + ".books where valid = 1 order by id desc"
        sql = "select * from " + db + ".books order by id desc"
        connected.cur.execute(sql)
        # connected.cur.execute('select * from ' + db + '.roast where valid = 1 order by id desc limit ' + str(limit))
        result_set = connected.cur.fetchall()
        resp_data = []
        for record in result_set:
            temp_dict = dict()
            temp_dict['id'] = record[0]
            temp_dict['book_name'] = record[1]
            temp_dict['book_code'] = record[2]
            temp_dict['book_author'] = record[3]
            temp_dict['borrow_status'] = record[4]
            temp_dict['book_valid'] = record[5]
            temp_dict['creation_ts'] = record[-1]
            resp_data.append(temp_dict)
        # 关闭游标
        connected.cur.close()
        # 关闭数据库连接
        connected.con.close()
        return {'result': 'success', 'content': resp_data, 'count': len(resp_data)}
